package com.wltt.product.ahuthr.service;

import com.wltt.product.ahuthr.config.exception.BusinessException;
import com.wltt.product.ahuthr.mapper.AttachFileMapper;
import com.wltt.product.ahuthr.model.ResultData;
import com.wltt.product.ahuthr.model.po.AttachFilePO;
import com.wltt.product.ahuthr.model.vo.FileUploadRsp;
import com.wltt.product.ahuthr.model.vo.base.AttachFileVO;
import com.wltt.product.ahuthr.utils.FileUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService{

    @Resource
    private AttachFileMapper attachFileMapper;

    /**
     * 上传
     *
     * @return
     */
    @Override
    @Transactional
    public ResultData upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException("未上传文件", HttpStatus.BAD_REQUEST);
        }

        // 文件名
        String fileName = file.getOriginalFilename();
        String suffix = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf("."));
        String destName = UUID.randomUUID() + suffix;

        // 保存记录
        AttachFilePO attachFilePO = new AttachFilePO();
        attachFilePO.setFileSourceName(fileName);
        attachFilePO.setFileSaveName(destName);
        attachFilePO.setFileSize(file.getSize());
        attachFilePO.setFileContent(file.getBytes());
        attachFilePO.setFileUploadTime(new Date());
        attachFileMapper.insertSelective(attachFilePO);

        FileUploadRsp rsp = new FileUploadRsp();
        BeanUtils.copyProperties(attachFilePO, rsp);

        return ResultData.success(rsp);
    }

    /**
     * 下载文件
     *
     * @param response
     * @param fileSaveName
     * @return
     */
    @Override
    public void getImage(HttpServletResponse response, String fileSaveName) throws IOException {
        if (null == fileSaveName || "".equals(fileSaveName.trim())) {
            throw new BusinessException("未指定文件", HttpStatus.BAD_REQUEST);
        }
        AttachFilePO attachFilePO = attachFileMapper.queryBySaveName(fileSaveName);
        if (null == attachFilePO) {
            throw new BusinessException("文件不存在", HttpStatus.BAD_REQUEST);
        }

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        bos.write( attachFilePO.getFileContent());
        bos.flush();
    }
}
